# 括号内为随机数
import json
import pickle
import random
import sys
import time

import facade
from xjlibrary.mdatetime.mtime import getTodayDate
from xjlibrary.our_file_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
cookiedir = BaseDir.get_new_path(curPath, "cookies")


class Login():

    def __init__(self):
        self.url = "http://search.cnipr.com/login.action?rd={}"
        self.headers = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded",
            "Host": "search.cnipr.com",
            "Origin": "http://search.cnipr.com",
            "Pragma": "no-cache",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest",
            # "X-Ultra-Id": "CNIPR002^1544130424277^10466;r=44309376"
        }
        self.postdata = {
            "username": "xujiang5",
            "password": "xujiang1994323"
        }
        self.logger = facade.get_streamlogger()
        self.cookiepath = ""

    def login(self,retrynum=0):
        if retrynum > 2:
            self.logger.info("重试3次登陆失败 现在结束程序等待检查")
            sys.exit(-1)
        self.url = self.url.format(random.random())
        BoolResult, errString, r = facade.BaseRequestPost(self.url,
                                                          data=self.postdata,
                                                          endstring="",
                                                          mark="msg",
                                                          headers=self.headers,
                                                          )

        def write_file():
            self.logger.info("将cookie写入文件")
            cookiename = str(getTodayDate()) + ".txt"
            # cookie按外网地址和今天的时间为登陆的cookie文件命名
            self.cookiepath = BaseDir.get_new_path(cookiedir, cookiename)
            with open(self.cookiepath, "wb") as f:
                pickle.dump(r.cookies, f)
            return True

        if BoolResult:
            if json.loads(r.text)["msg"] == "alreadylogin":
                url = "http://search.cnipr.com/login!goonlogin.action?rd={}".format(random.random())
                BoolResult, errString, r = facade.BaseRequestPost(url,
                                                                  data=self.postdata,
                                                                  endstring="",
                                                                  mark="msg",
                                                                  # headers=headers,
                                                                  )
                if BoolResult:
                    write_file()
            else:
                write_file()
            return True
        else:
            self.logger.info("登陆失败 重试3次")
            self.logger.error(errString)
            self.logger.info("休眠1分钟后登陆.....")
            time.sleep(60)
            retrynum += 1
            self.login(retrynum)


if __name__ == "__main__":
    login = Login()
    login.login()
